<template>
  <div class="chat-gpt">
    <!-- 聊天列表 -->
    <!-- <div class="chat-gpt-left">
      <div class="item_btn" @click="createNewChat">新建聊天</div>
      <div class="item_c_list">
        <div
          class="item_c"
          :class="{ active: activeIndex == index }"
          v-for="(chat, index) in chatList"
          :key="index"
          @click="selectChat(index)"
        >
          <p><i class="el-icon-chat-line-round"></i>{{ chat.title }}</p>
          <p>
            <i class="el-icon-delete" @click.stop="deleteChat(index)"></i>
          </p>
        </div>
      </div>
    </div> -->
    <div class="input-area-tit">
      <span>您可以输入省市区来查询区域负责人的信息！</span>
      <div>
        <i
          v-if="miniFlag"
          class="el-icon-minus"
          style="cursor: pointer; margin-right: 10px"
          @click="handleMini"
        ></i>
        <i
          v-else
          class="el-icon-full-screen"
          style="cursor: pointer; margin-right: 10px"
          @click="handleBig"
        ></i>
        <i
          class="el-icon-close"
          style="cursor: pointer"
          @click="handleClose"
        ></i>
      </div>
    </div>
    <div class="chat-gpt-right" v-if="currentChat !== null">
      <div class="chat-area" ref="messageList">
        <div
          v-for="(message, index) in currentChat.messages"
          :key="index"
          class="message"
        >
          <!-- 根据消息发送者动态添加样式 -->
          <div
            v-if="message.sender === 'machine'"
            class="message-bubble machine-response"
          >
            <!-- <div class="c_name">AI</div> -->
            <div class="c_cont">
              <div
                :style="
                  message.answerInfo && imgShow
                    ? 'border-bottom: 1px dashed #979DAE;padding-bottom: 9px;width:100%'
                    : ''
                "
              >
                {{ message.text }}
              </div>
              <div v-if="imgShow" style="margin-top: 8px; width: 100%">
                <!-- <div v-if="!message.qrcode && !message.remark">
                  <div
                    v-for="(item, index) in message.answerInfo"
                    :key="index"
                    style="
                      padding: 6px 0px;
                      display: flex;
                      align-item: center;
                      display: flex;
                      flex-direction: column;
                    "
                  >
                    <div
                      style="
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                      "
                    >
                      <div>
                        <img
                          :src="index % 2 === 0 ? iponeBlue : iponeYellow"
                          alt=""
                          style="width: 20px; height: 20px; margin-right: 8px"
                        />
                        {{ item.answer }}
                      </div>
                    </div>
                  </div>
                </div> -->

                <!-- :disabled="!message.qrcode && !message.remark" -->
                <div v-if="message.answerInfo">
                  <el-collapse
                    v-for="(item, index) in message.answerInfo"
                    :key="index"
                  >
                    <el-collapse-item v-if="item.qrcode || item.remark">
                      <template slot="title">
                        <div
                          style="
                            display: flex;
                            justify-content: space-between;
                            align-items: center;
                          "
                        >
                          <div style="white-space: nowrap">
                            <img
                              :src="index % 2 === 0 ? iponeBlue : iponeYellow"
                              alt=""
                              style="
                                width: 20px;
                                height: 20px;
                                margin-left: 14px;
                                margin-right: 8px;
                              "
                            />
                            <el-dropdown v-if="item.city">
                              <span class="el-dropdown-link">
                                {{ `（${item.province}）` + item.answer }}
                              </span>
                              <el-dropdown-menu slot="dropdown" class="lang-select-dropdown"  style="max-width:200px">
                                <el-dropdown-item >{{
                                  item.city
                                }}</el-dropdown-item>
                              </el-dropdown-menu>
                            </el-dropdown>
                            <div v-else>
                              {{ `（${item.province}）` + item.answer }}
                            </div>
                            <!-- {{ `（${item.province}）` + item.answer }} -->
                            <!-- {{`(${
                                item.province == item.area ? "" : item.province
                              }${item.area})` +
                              item.answer.split("，").join(" ")}} -->
                          </div>
                        </div>
                      </template>
                      <div style="width: 100%; margin-left: 16px">
                        <div style="display: flex" v-if="item.remark">
                          <div
                            style="
                              width: 26px;
                              text-align: end;
                              white-space: nowrap;
                            "
                          >
                            备注：
                          </div>
                          <div style="margin-left: 22px; max-width: 130px">
                            {{ item.remark ? item.remark : "暂无" }}
                          </div>
                        </div>
                        <div
                          style="display: flex; margin-top: 10px"
                          v-if="item.qrcode"
                        >
                          <div
                            style="
                              width: 26px;
                              text-align: end;
                              white-space: nowrap;
                            "
                          >
                            二维码：
                          </div>
                          <img
                            style="
                              width: 100px;
                              height: 100px;
                              margin: 0px 24px;
                              margin-top: 4px;
                            "
                            :src="item.qrcode"
                            alt=""
                          />
                          <!-- <span v-else style="margin-left: 23px">暂无</span> -->
                        </div>
                      </div>
                    </el-collapse-item>
                    <div
                      v-else
                      style="
                        padding: 6px 0px;
                        display: flex;
                        align-item: center;
                        display: flex;
                        flex-direction: column;
                      "
                    >
                      <div
                        style="
                          display: flex;
                          justify-content: space-between;
                          align-items: center;
                        "
                      >
                        <div style="display: flex; align-items: center">
                          <img
                            :src="index % 2 === 0 ? iponeBlue : iponeYellow"
                            alt=""
                            style="
                              width: 20px;
                              height: 20px;
                              margin-right: 8px;
                              margin-left: 14px;
                            "
                          />
                          <el-dropdown v-if="item.city">
                            <span class="el-dropdown-link">
                              {{ `（${item.province}）` + item.answer
                              }}
                            </span>
                            <el-dropdown-menu slot="dropdown" style="max-width:200px">
                              <el-dropdown-item >{{
                                item.city
                              }}</el-dropdown-item>
                            </el-dropdown-menu>
                          </el-dropdown>
                          <div v-else>
                            {{ `（${item.province}）` + item.answer }}
                          </div>
                          <!-- {{`(${
                                item.province == item.area ? "" : item.province
                              }${item.area})` +
                              item.answer.split("，").join(" ")}} -->
                        </div>
                      </div>
                    </div>
                  </el-collapse>
                </div>
                <!-- <div
                  v-for="(item, index) in message.answerInfo"
                  :key="index"
                  style="
                    padding: 6px 0px;
                    display: flex;
                    align-item: center;
                    display: flex;
                    flex-direction: column;
                  "
                >
                  <div
                    style="
                      display: flex;
                      justify-content: space-between;
                      align-items: center;
                    "
                  >
                    <div>
                      <img
                        :src="index % 2 === 0 ? iponeBlue : iponeYellow"
                        alt=""
                        style="width: 20px; height: 20px; margin-right: 8px"
                      />
                      {{ item.split("@")[0].split("，").join(" ") }}
                    </div>
                    <i class="el-icon-arrow-down" style="margin-left:10px" ></i>
                  </div>
                  <img
                    style="width: 100px; height: 100px; margin: 10px auto"
                    v-if="item.split('@')[1]" 
                    :src="item.split('@')[1]"
                    alt=""
                  />
                </div> -->
              </div>
            </div>
          </div>
          <div
            v-else-if="message.sender === 'me'"
            class="message-bubble user-message"
          >
            <div
              class="c_cont"
              style="background: #e0dfff; border-radius: 36px 0px 36px 36px"
            >
              {{ message.text }}
            </div>
            <!-- <div class="c_name">我</div> -->
          </div>
        </div>
      </div>
      <div class="input-area">
        <el-input
          style="width: 100%; height: 90px !important"
          type="textarea"
          v-model="formData.inputMessage"
          placeholder="请输入您想查询的地区"
          resize="none"
        ></el-input>
        <el-button
          type="primary"
          @click="sendMessage"
          size="mini"
          style="position: absolute; right: 4px; bottom: 12px"
          >发送</el-button
        >
      </div>
    </div>
    <div class="chat-gpt-right" v-else>
      <div>
        <p>请选择一个聊天</p>
      </div>
    </div>
  </div>
</template>

<script>
import { robotAnswer } from "@/api/homePage.js";
import { STATUS_CODE_OK } from "@/config";
import iponeYellow from "@/assets/images/gpt_ipone1.png";
import iponeBlue from "@/assets/images/gpt_ipone2.png";
// import chatData from "./chatData.json";
export default {
  name: "ChatBot",
  props: {
    dataList: {
      type: Array,
      default() {
        return [];
      },
    },
    robotBottom: {
      type: String,
      default() {
        return "";
      },
    },
  },
  data() {
    return {
      miniFlag: true,
      isShow: true,
      iponeBlue,
      iponeYellow,
      optimizedCode: false,
      formData: {
        inputMessage: "",
      },
      messages: [],
      chatList: [], // 存储聊天列表
      currentChat: null, // 存储当前选中的聊天
      activeIndex: null,
      imgShow: false,
      isRobotReplying: false, // 添加 isRobotReplying 属性
    };
  },
  watch: {
    dataList(newValue) {
      this.chatData = newValue;
    },
    robotBottom(newValue) {
      if (newValue == "10px") {
        window.addEventListener("keydown", this.keyDown);
        this.miniFlag = true;
      } else {
        this.miniFlag = false;
        window.removeEventListener("keydown", this.keyDown, false);
      }
    },
  },
  mounted() {
    window.addEventListener("keydown", this.keyDown);
    this.createNewChat();
  },
  updated() {
    this.scrollToBottom(); // 当组件更新时，确保滚动到底部
  },
  destroyed() {
    window.removeEventListener("keydown", this.keyDown, false);
  },
  methods: {
    async handleRobotAnswer(question = "") {
      let { data } = await robotAnswer({
        question: question,
      });
      if (data.code == STATUS_CODE_OK) {
        return data.data;
      }
    },
    // 点击回车键登录
    keyDown(e) {
      // 点击回车键执行登录方法 enter键的ASCII是13
      if (e.keyCode === 13) {
        this.sendMessage();
      }
    },
    // 缩小
    handleMini() {
      this.miniFlag = false;
      this.$emit("handleMini", "-425px");
    },
    // 放大
    handleBig() {
      this.miniFlag = true;
      this.$emit("handleBig", "10px");
    },
    handleClose() {
      this.$emit("handleClose", false);
    },
    // 组件更新滚动到底部
    scrollToBottom() {
      this.$nextTick(() => {
        const messageList = this.$refs.messageList;
        messageList.scrollTop = messageList.scrollHeight;
      });
    },
    // 创建新聊天
    createNewChat() {
      const newChat = {
        title: "New Chat", // 聊天标题
        messages: [
          {
            sender: "machine",
            text: "您可以输入省市区来查询区域负责人的信息，按照格式会更准确哦，格式：xx省(自治区) xx市 xx区(县)！",
          },
        ], // 聊天消息
      };
      this.chatList.push(newChat);
      this.formData.inputMessage = "";
      // 恢复发送按钮和输入数据
      this.isRobotReplying = false;
      this.selectChat(this.chatList.length - 1); // 选择新创建的聊天
    },
    // // 选择聊天
    selectChat(index) {
      this.currentChat = this.chatList[index];
      this.activeIndex = index;
    },
    // // 编辑聊天
    // editChat() {
    //   // 处理编辑聊天的逻辑
    //   console.log(1);
    // },
    // 删除聊天
    deleteChat(index) {
      this.chatList.splice(index, 1);
      if (this.chatList.length > 0) {
        this.selectChat(0); // 选择第一个聊天
        this.activeIndex = 0;
      } else {
        this.currentChat = null; // 如果没有聊天了，清空当前聊天
        this.activeIndex = null;
      }
    },

    async sendMessage() {
      if (!this.formData.inputMessage) {
        return false;
      }
      this.imgShow = false;
      const userMessage = this.formData.inputMessage;
      // 发送之后清空输入框
      this.formData.inputMessage = "";
      const currentChatNow = this.currentChat; // 获取当前选中的聊天
      // 设置标题，您可以根据需要更改
      currentChatNow.title = userMessage;

      // 禁用发送按钮和输入数据
      this.isRobotReplying = true;

      // 用户消息
      const userMessageObj = { sender: "me", text: "" };
      currentChatNow.messages.push(userMessageObj);
      const userMessageLetters = userMessage.split(""); // 将用户消息拆分成字 母数组
      const matchedQuestion = await this.handleRobotAnswer(userMessage);
      for (const letter of userMessageLetters) {
        userMessageObj.text += letter;
        // await this.delay(100); // 添加延迟以逐字显示
      }

      if (matchedQuestion.length > 0) {
        let answer = `为您查询到‘${userMessage}’相关负责人信息：（若查询的地区为省份移入鼠标可查看地区详情）`;
        let answerInfo = [];
        let area = "";
        // 是否可以回答
        let isAnswer = true;
        for (let index = 0; index < matchedQuestion.length; index++) {
          // const answer = matchedQuestion[index].answer;
          answerInfo.push({
            answer: matchedQuestion[index].answer,
            qrcode: matchedQuestion[index].qrcode,
            remark: matchedQuestion[index].remark,
            area: matchedQuestion[index].question,
            province: matchedQuestion[index].province,
            city: matchedQuestion[index].city,
          });
          area = matchedQuestion[index].question;
        }
        // 机器回复
        const machineResponseObj = {
          sender: "machine",
          text: "",
          isAnswer: isAnswer,
          area: area,
          answerInfo: answerInfo,
        };
        currentChatNow.messages.push(machineResponseObj);
        const answerLetters = answer.split(""); // 将回复拆分成字母数组

        for (const letter of answerLetters) {
          machineResponseObj.text += letter;
          await this.delay(100); // 添加延迟以逐字显示
        }
        // 二维码展示
        setTimeout(() => {
          this.imgShow = true;
        }, 200);
      } else {
        // 如果找不到相似的问题，您可以提供默认回复或其他处理逻辑
        // const defaultResponse = "抱歉，我暂时无法回答您的问题。";
        const defaultResponse = `抱歉，我暂时没有找到‘${userMessage}’区域的负责人信息，您可以按照这种格式搜索更准确哦~，例如：湖南省长沙市雨花区。`;
        // 机器回复
        const machineResponseObj = { sender: "machine", text: "" };
        currentChatNow.messages.push(machineResponseObj);

        const defaultResponseLetters = defaultResponse.split(""); // 将默认回复拆分成字母数组

        for (const letter of defaultResponseLetters) {
          machineResponseObj.text += letter;
          await this.delay(100); // 添加延迟以逐字显示
        }
        setTimeout(() => {
          this.imgShow = true;
        }, 200);
      }
      this.formData.inputMessage = "";

      // 恢复发送按钮和输入数据
      this.isRobotReplying = false;
    },

    // 一次性请求所有数据
    // async sendMessage() {
    //   if (!this.formData.inputMessage) {
    //     return false;
    //   }

    //   this.imgShow = false;
    //   const userMessage = this.formData.inputMessage;
    //   // 发送之后清空输入框
    //   this.formData.inputMessage = "";
    //   const currentChatNow = this.currentChat; // 获取当前选中的聊天
    //   // 设置标题，您可以根据需要更改
    //   currentChatNow.title = userMessage;

    //   // 禁用发送按钮和输入数据
    //   this.isRobotReplying = true;

    //   // 用户消息
    //   const userMessageObj = { sender: "me", text: "" };
    //   currentChatNow.messages.push(userMessageObj);

    //   const userMessageLetters = userMessage.split(""); // 将用户消息拆分成字 母数组

    //   for (const letter of userMessageLetters) {
    //     userMessageObj.text += letter;
    //     // await this.delay(100); // 添加延迟以逐字显示
    //   }
    //   if (
    //     userMessage == "省市区" ||
    //     userMessage == "省区市" ||
    //     userMessage == "市区省" ||
    //     userMessage == "市省区" ||
    //     userMessage == "区省市" ||
    //     userMessage == "省区" ||
    //     userMessage == "省市" ||
    //     userMessage == "区省" ||
    //     userMessage == "区市" ||
    //     userMessage == "市区" ||
    //     userMessage == "市省" ||
    //     userMessage == "区" ||
    //     userMessage == "市" ||
    //     userMessage == "省"
    //   ) {
    //     const defaultResponse = `抱歉，我暂时没有找到‘${userMessage}’区域的负责人信息，您可以按照这种格式搜索更准确哦~，例如：湖南省长沙市雨花区。`;
    //     // 机器回复
    //     const machineResponseObj = { sender: "machine", text: "" };
    //     currentChatNow.messages.push(machineResponseObj);

    //     const defaultResponseLetters = defaultResponse.split(""); // 将默认回复拆分成字母数组

    //     for (const letter of defaultResponseLetters) {
    //       machineResponseObj.text += letter;
    //       await this.delay(100); // 添加延迟以逐字显示
    //     }
    //     setTimeout(() => {
    //       this.imgShow = true;
    //     }, 200);
    //     return false;
    //   }
    //   // 预处理输入字符串，拆分成多个部分
    //   const parts = userMessage.split(/省|市|州|区|县/).filter(Boolean);
    //   let finalMessage = parts[parts.length - 1]; // 默认取最后一部分作为主要匹配项

    //   // 模糊匹配用户消息与 this.chatData 中的问题
    //   const matchedQuestionList = this.findSimilarQuestion(finalMessage);
    //   // 模糊匹配用户消息与 this.chatData.json 中的问题
    //   // const matchedQuestion = this.matchQuestion(userMessage);
    //   // const matchedQuestion = this.findSimilarQuestion(userMessage);
    //   // 去重
    //   const matchedQuestion = matchedQuestionList.reduce((acc, current) => {
    //     const x = acc.find(
    //       (item) =>
    //         item.answer === current.answer && item.question === current.question
    //     );
    //     if (!x) {
    //       return acc.concat([current]);
    //     } else {
    //       return acc;
    //     }
    //   }, []);
    //   if (matchedQuestion.length > 0) {
    //     let answer = `为您查询到‘${userMessage}’相关负责人信息：`;
    //     let answerInfo = [];
    //     let area = "";
    //     // 是否可以回答
    //     let isAnswer = true;
    //     for (let index = 0; index < matchedQuestion.length; index++) {
    //       // const answer = matchedQuestion[index].answer;
    //       answerInfo.push({
    //         answer: matchedQuestion[index].answer,
    //         qrcode: matchedQuestion[index].qrcode,
    //         remark: matchedQuestion[index].remark,
    //         area: matchedQuestion[index].question,
    //         province: matchedQuestion[index].province,
    //       });
    //       area = matchedQuestion[index].question;
    //     }
    //     // 机器回复
    //     const machineResponseObj = {
    //       sender: "machine",
    //       text: "",
    //       isAnswer: isAnswer,
    //       area: area,
    //       answerInfo: answerInfo,
    //     };
    //     currentChatNow.messages.push(machineResponseObj);
    //     const answerLetters = answer.split(""); // 将回复拆分成字母数组

    //     for (const letter of answerLetters) {
    //       machineResponseObj.text += letter;
    //       await this.delay(100); // 添加延迟以逐字显示
    //     }
    //     // 二维码展示
    //     setTimeout(() => {
    //       this.imgShow = true;
    //     }, 200);
    //     // const answer = matchedQuestion.answer;
    //     // // 机器回复
    //     // const machineResponseObj = { sender: "machine", text: "" };
    //     // currentChatNow.messages.push(machineResponseObj);

    //     // const answerLetters = answer.split(""); // 将回复拆分成字母数组

    //     // for (const letter of answerLetters) {
    //     //   machineResponseObj.text += letter;
    //     //   await this.delay(100); // 添加延迟以逐字显示
    //     // }
    //   } else {
    //     // 如果未找到匹配的问题，尝试查找类似的问题并返回相关答案
    //     const similarQuestion = this.findSimilarQuestion(userMessage);
    //     let answer = `为您查询到${userMessage}相关负责人信息：`;
    //     let answerInfo = [];
    //     let qrcode = "";
    //     let area = "";
    //     // 是否可以回答
    //     const isAnswer = true;
    //     if (similarQuestion.length > 0) {
    //       for (let index = 0; index < similarQuestion.length; index++) {
    //         // answerInfo = similarQuestion[index].answer;
    //         answerInfo.push({
    //           answer: similarQuestion[index].answer,
    //           qrcode: similarQuestion[index].qrcode,
    //           remark: similarQuestion[index].remark,
    //         });
    //         area = similarQuestion[index].question;
    //       }
    //       // 机器回复
    //       const machineResponseObj = {
    //         sender: "machine",
    //         text: "",
    //         qrcode: qrcode,
    //         isAnswer: isAnswer,
    //         area: area,
    //         answerInfo: answerInfo,
    //       };
    //       currentChatNow.messages.push(machineResponseObj);
    //       const answerLetters = answer.split(""); // 将回复拆分成字母数组
    //       for (const letter of answerLetters) {
    //         machineResponseObj.text += letter;
    //         await this.delay(100); // 添加延迟以逐字显示
    //       }
    //       // 二维码展示
    //       setTimeout(() => {
    //         this.imgShow = true;
    //       }, 200);
    //       // const answer = similarQuestion.answer;
    //       // // 机器回复
    //       // const machineResponseObj = { sender: "machine", text: "" };
    //       // currentChatNow.messages.push(machineResponseObj);

    //       // const answerLetters = answer.split(""); // 将回复拆分成字母数组

    //       // for (const letter of answerLetters) {
    //       //   machineResponseObj.text += letter;
    //       //   await this.delay(100); // 添加延迟以逐字显示
    //       // }
    //     } else {
    //       // 如果找不到相似的问题，您可以提供默认回复或其他处理逻辑
    //       // const defaultResponse = "抱歉，我暂时无法回答您的问题。";
    //       const defaultResponse = `抱歉，我暂时没有找到‘${userMessage}’区域的负责人信息，您可以按照这种格式搜索更准确哦~，例如：湖南省长沙市雨花区。`;
    //       // 机器回复
    //       const machineResponseObj = { sender: "machine", text: "" };
    //       currentChatNow.messages.push(machineResponseObj);

    //       const defaultResponseLetters = defaultResponse.split(""); // 将默认回复拆分成字母数组

    //       for (const letter of defaultResponseLetters) {
    //         machineResponseObj.text += letter;
    //         await this.delay(100); // 添加延迟以逐字显示
    //       }
    //       setTimeout(() => {
    //         this.imgShow = true;
    //       }, 200);
    //     }
    //     // if (similarQuestion) {
    //     //   const answer = similarQuestion.answer;
    //     //   // 机器回复
    //     //   const machineResponseObj = { sender: "machine", text: "" };
    //     //   currentChatNow.messages.push(machineResponseObj);

    //     //   const answerLetters = answer.split(""); // 将回复拆分成字母数组

    //     //   for (const letter of answerLetters) {
    //     //     machineResponseObj.text += letter;
    //     //     await this.delay(100); // 添加延迟以逐字显示
    //     //   }
    //     // } else {
    //     //   // 如果找不到相似的问题，您可以提供默认回复或其他处理逻辑
    //     //   // const defaultResponse = "抱歉，我暂时无法回答您的问题。";
    //     //   const defaultResponse = `抱歉，我暂时没有找到‘${userMessage}’区域的负责人信息。`;
    //     //   // 机器回复
    //     //   const machineResponseObj = { sender: "machine", text: "" };
    //     //   currentChatNow.messages.push(machineResponseObj);

    //     //   const defaultResponseLetters = defaultResponse.split(""); // 将默认回复拆分成字母数组

    //     //   for (const letter of defaultResponseLetters) {
    //     //     machineResponseObj.text += letter;
    //     //     await this.delay(100); // 添加延迟以逐字显示
    //     //   }
    //     // }
    //   }
    //   this.formData.inputMessage = "";

    //   // 恢复发送按钮和输入数据
    //   this.isRobotReplying = false;
    // },
    async typeResponse(response, currentChatNow) {
      const characters = response.split("");
      for (const char of characters) {
        await this.delay(100); // 延迟控制逐字显示速度，可以根据需要调整
        currentChatNow.messages[currentChatNow.messages.length - 1].text +=
          char;
      }
    },
    // 添加延迟函数
    delay(ms) {
      return new Promise((resolve) => setTimeout(resolve, ms));
    },
    // 模糊匹配用户消息与 this.chatData.json 中的问题
    // matchQuestion(userMessage) {
    //   const lowerCaseUserMessage = userMessage.toLowerCase();
    //   let bestMatch = null;
    //   let bestRatio = 0.5;
    //   for (const questionData of this.chatData) {
    //     const lowerCaseQuestion = questionData.question.toLowerCase();
    //     const similarityRatio = this.calculateSimilarity(
    //       lowerCaseUserMessage,
    //       lowerCaseQuestion
    //     );
    //     if (similarityRatio > bestRatio) {
    //       bestRatio = similarityRatio;
    //       bestMatch = questionData;
    //     }
    //   }
    //   // // 只有当相似度大于某个阈值时才返回匹配的问题，否则返回 null

    //   if (bestRatio >= 0.7) {
    //     return bestMatch;
    //   } else {
    //     return null;
    //   }
    // },
    // 定义 findSimilarQuestion 方法
    findSimilarQuestion(userMessage) {
      // 创建一个数组来存储匹配程度最高的问题
      let bestMatchedQuestions = [];
      // 匹配的阀值
      let bestMatchRatio = 0.5;
      // 遍历 this.chatData 中的问题，计算与用户消息的相似度
      for (const questionData of this.chatData) {
        const similarityRatio = this.calculateSimilarity(
          userMessage.toLowerCase(),
          questionData.question.toLowerCase()
        );

        // 如果相似度高于阈值，将问题添加到最佳匹配问题数组中
        if (similarityRatio > bestMatchRatio) {
          bestMatchedQuestions = [questionData];
          bestMatchRatio = similarityRatio;
        } else if (similarityRatio === bestMatchRatio) {
          // 如果相似度与当前最佳匹配相等，将问题添加到最佳匹配问题数组中
          bestMatchedQuestions.push(questionData);
        }
      }
      console.log(bestMatchedQuestions, "bestMatchedQuestions");
      return bestMatchedQuestions;
      // // 如果找到了最佳匹配问题，从中随机选择一个问题返回
      // if (bestMatchedQuestions.length > 0) {
      //   const randomIndex = Math.floor(
      //     Math.random() * bestMatchedQuestions.length
      //   );
      //   console.log(bestMatchedQuestions,'bestMatchedQuestions');
      //   return bestMatchedQuestions[randomIndex];
      // } else {
      //   // 如果找不到相似问题，返回 null
      //   return null;
      // }
    },
    longestCommonSubstring(str1, str2) {
      let matrix = [];
      let longest = 0;
      let x_longest = 0;

      for (let x = 0; x < str1.length; x++) {
        matrix[x] = [];
        for (let y = 0; y < str2.length; y++) {
          if (str1[x] === str2[y]) {
            if (x === 0 || y === 0) {
              matrix[x][y] = 1;
            } else {
              matrix[x][y] = matrix[x - 1][y - 1] + 1;
            }
            if (matrix[x][y] > longest) {
              longest = matrix[x][y];
              x_longest = x;
            }
          } else {
            matrix[x][y] = 0;
          }
        }
      }
      return str1.substring(x_longest - longest + 1, x_longest + 1);
    },
    // 计算两个字符串的相似度
    calculateSimilarity(str1, str2) {
      // 检查查询字符串是否是目标字符串的一部分
      // if (str2.includes(str1)) {

      //   return 1;
      // }

      const lcs = this.longestCommonSubstring(str1, str2);
      return lcs.length / str1.length;
      // // 这里使用一种简单的相似度计算方法，您也可以使用更高级的算法
      // const longer = str1.length > str2.length ? str1 : str2;
      // const shorter = str1.length > str2.length ? str2 : str1;
      // const longerLength = longer.length;
      // if (longerLength === 0) {
      //   return 1.0;
      // }

      // return (
      //   (longerLength - this.calculateEditDistance(longer, shorter)) /
      //   parseFloat(longerLength)
      // );
    },
    // 计算编辑距离（Edit Distance）
    calculateEditDistance(str1, str2) {
      console.log(str1, str2, "matrix");
      // 这是一个常见的编辑距离算法，用于计算两个字符串之间的距离
      // 您可以根据需要使用更高级的算法
      const matrix = [];

      for (let i = 0; i <= str2.length; i++) {
        matrix[i] = [i];
      }

      for (let j = 0; j <= str1.length; j++) {
        matrix[0][j] = j;
      }

      for (let i = 1; i <= str2.length; i++) {
        for (let j = 1; j <= str1.length; j++) {
          if (str2.charAt(i - 1) === str1.charAt(j - 1)) {
            matrix[i][j] = matrix[i - 1][j - 1];
          } else {
            matrix[i][j] = Math.min(
              matrix[i - 1][j - 1] + 1,
              Math.min(matrix[i][j - 1] + 1, matrix[i - 1][j] + 1)
            );
          }
        }
      }

      return matrix[str2.length][str1.length];
    },
  },
};
</script>

<style lang="scss" scoped>
.el-collapse-item__arrow{
margin:auto !important;
}
.lang-select-dropdown {
  margin-left: -130px;
  margin-top: -10px;
}
::v-deep .el-dropdown {
  color: #333;
}
::v-deep .el-collapse-item__header {
  background: #eff1f7;
  max-width: 320px;
}
::v-deep .el-collapse-item__wrap {
  background-color: #eff1f7;
}
::v-deep .el-collapse-item.is-disabled .el-collapse-item__header {
  color: #000;
  cursor: pointer;
}
$color_1: #18a058;
.chat-gpt {
  width: 458px;
  height: 472px;
  background: #ffffff;
  box-shadow: 0px 3px 8px 1px rgba(0, 0, 0, 0.1);
  border-radius: 8px 8px 8px 8px;
  // width: 100%;
  // // height: 500px;
  // overflow: hidden;
  // display: flex;
  // font-size: 0.8333vw;

  /* 逐字显示动画 */
  .message-bubble {
    overflow: hidden;
  }

  .message-bubble[data-typing]::after {
    content: "";
    animation: typing 0.1s steps(1) infinite;
  }

  @keyframes typing {
    0% {
      width: 0;
    }

    100% {
      width: 100%;
    }
  }

  .machine-response {
    display: flex;
    align-items: flex-start;
    justify-content: flex-start;
  }

  .user-message {
    display: flex;
    align-items: flex-start;
    justify-content: flex-end;
  }

  .chat-gpt-left {
    width: 20.8333vw;
    border: 1px solid #ccc;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 1.0417vw 1.5625vw;
    min-width: 200px;

    .item_btn {
      width: 100%;
      margin: 0.5208vw 0;
      background-color: $color_1;
      color: #fff;
      height: 2.9167vw;
      border-radius: 0.4167vw;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
    }

    .item_c_list {
      width: 100%;
      flex: 1;
      width: 100%;
      display: flex;
      flex-direction: column;

      .item_c {
        width: 100%;
        display: flex;
        align-items: center;
        border: 1px solid #ccc;
        height: 2.9167vw;
        justify-content: space-between;
        color: $color_1;
        border-radius: 0.3125vw;
        margin: 0 0 0.5208vw 0;
        cursor: pointer;

        p {
          display: flex;
          align-items: center;

          &:nth-child(1) {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            -webkit-line-clamp: 1;
            -webkit-box-orient: vertical;
          }
        }

        i {
          margin: 0 0.2604vw;
          font-size: 1.25vw;
          color: $color_1;
          cursor: pointer;
        }

        &.active {
          border: 1px solid $color_1;
          background: rgba($color: $color_1, $alpha: 0.1);
        }
      }
    }
  }
  .input-area-tit {
    width: 458px;
    height: 48px;
    background: #005fec;
    color: #fff;
    font-weight: 400;
    font-size: 14px;
    border-radius: 4px 4px 0px 0px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0px 10px 0px 30px;
  }
  .chat-gpt-right {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    position: relative;
    padding: 0.5208vw;

    .chat-area {
      // flex: 1;
      height: 300px;
      display: flex;
      flex-direction: column;
      overflow-y: auto;

      .message {
        .message-bubble {
          margin-bottom: 1.0417vw;
        }

        .c_name {
          width: 2.6042vw;
          height: 2.6042vw;
          display: flex;
          align-items: center;
          justify-content: center;
          background-color: #18a058;
          border-radius: 50%;
          color: #fff;
          font-size: 0.8333vw;
          font-weight: 600;
          margin: 1.0417vw 0.5208vw 0 0.5208vw;
        }

        .c_cont {
          // flex: 1;
          // border-radius: 0.3125vw;
          // background-color: #efefef;
          // min-height: 4.1667vw;
          // max-width: calc(100% - 15.625vw);
          padding: 0.5208vw 1.0417vw;
          justify-content: center;
          max-width: 384px;
          min-height: 52px;
          background: #eff1f7;
          border-radius: 0px 36px 36px 36px;
          font-weight: 400;
          font-size: 14px;
          color: #333333;
          display: flex;
          align-items: flex-start;
          flex-direction: column;
        }
      }
    }

    .input-area {
      width: 100%;
      display: flex;
      align-items: flex-end;
      height: 94px;
      .el-textarea {
        height: 100% !important;
        display: flex;

        .el-textarea__inner {
          height: 100% !important;
        }
      }

      .el-button {
        margin: 0 0.5208vw;
      }
    }
  }
}

.vue-codemirror {
  width: 100%;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.CodeMirror {
  height: auto !important;
  flex: 1;
}

.CodeMirror-sizer {
  margin-bottom: 0 !important;
}
</style>
